package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.dto.RoleDto;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.RoleUser;
import com.itheima.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.RoleMapper;
import com.itheima.pojo.Role;
import com.itheima.service.RoleUserService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    private RoleUserService roleUserService;


    @Override
    @Transactional
    public boolean addRole(RoleDto roleDto) {
        //保存角色信息
        this.saveOrUpdate(roleDto.getRole());

        //维护中间表
        //每进行修改时,先对表中数据进行删除,根据检查组的ID ,删除对应的检查项
        if (roleDto.getRole().getId()!=null){
            roleUserService.deleteUserIds(roleDto.getRole().getId());
        }

        //保存中间表信息
        ArrayList<RoleUser> roleUsers = new ArrayList<>();
        //遍历所有用户
        Long[] usersId = roleDto.getUsersId();
        for (Long i : usersId) {
            RoleUser roleUser = new RoleUser();
            //主键 自增回显,获取角色ID
            System.out.println(roleDto.getRole().getId());
            roleUser.setRoleId( roleDto.getRole().getId());
            //用户ID
            roleUser.setUserId(i);
            //添加到集合中
            //roleUsers.add(roleUser);
            roleUserService.save(roleUser);
        }
        //统一进行插入到中间表
        //roleUserService.saveBatch(roleUsers);
        return true;
    }

    @Override
    public List<Role> findAll() {
        List<Role> roleList = this.list();
        return roleList;
    }

    @Override
    public boolean delete(Long id) {
        //删除角色表
        this.removeById(id);
        //删除中间表
        roleUserService.deleteUserIds(id);
        return true;
    }

    @Override
    public List<Role> findRole(QueryPageBean queryPageBean) {
        //获取查询条件
        String queryString = queryPageBean.getQueryString();
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("role_name",queryString);
        List<Role> roleList = this.list(queryWrapper);
        return roleList;
    }
}